package com.woniu.common.util;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.alibaba.fastjson2.JSON;
import com.woniu.common.dto.UserDto;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;

import static com.woniu.common.constant.GlobalConstant.HEADER_TOKEN;


public class GetUserInfoUtil {
    public static UserDto getUserInfo() throws ParseException{
        // 获取请求
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert requestAttributes != null;
        HttpServletRequest request = requestAttributes.getRequest();

        // 从请求获取jwt
        String stringJwt = request.getHeader(HEADER_TOKEN);
        JWT jwt = JWTUtil.parseToken(stringJwt);
        String userString = jwt.getPayload("user").toString();
        return JSON.parseObject(userString, UserDto.class);
    }
}
